<template>
  <el-card shadow="hover">
    <template #header>
      <div class="card-header">
        <span>数据筛选</span>
        <el-tag type="info" size="small">当前: {{ filteredCount }} / {{ totalCount }} 条</el-tag>
      </div>
    </template>

    <el-form :model="filterForm" label-position="top">
      <!-- 时间范围筛选 -->
      <el-form-item label="时间范围">
        <div class="slider-labels">
          <span>{{ formatTime(filterForm.timeRange[0]) }}</span>
          <span>{{ formatTime(filterForm.timeRange[1]) }}</span>
        </div>
        <el-slider
            v-model="filterForm.timeRange"
            range
            :min="minTime"
            :max="maxTime"
            :step="0.01"
            :format-tooltip="formatTime"
            @change="handleSliderChange"
        />
      </el-form-item>

      <!-- 高度范围筛选 -->
      <el-form-item label="高度范围 (米)">
        <div class="slider-labels">
          <span>{{ filterForm.altitudeRange[0] }}m</span>
          <span>{{ filterForm.altitudeRange[1] }}m</span>
        </div>
        <el-slider
            v-model="filterForm.altitudeRange"
            range
            :min="0"
            :max="maxAltitude"
            :step="100"
            @change="handleSliderChange"
        />
      </el-form-item>

      <!-- 速度范围筛选 -->
      <el-form-item label="速度范围 (km/h)">
        <div class="slider-labels">
          <span>{{ filterForm.velocityRange[0] }}km/h</span>
          <span>{{ filterForm.velocityRange[1] }}km/h</span>
        </div>
        <el-slider
            v-model="filterForm.velocityRange"
            range
            :min="0"
            :max="maxVelocity"
            :step="10"
            @change="handleSliderChange"
        />
      </el-form-item>

      <!-- 航向角筛选 -->
      <el-form-item label="航向角">
        <el-select
            v-model="filterForm.heading"
            multiple
            placeholder="选择航向角"
            clearable
            @change="applyFilters"
        >
          <el-option
              v-for="angle in headingOptions"
              :key="angle.value"
              :label="angle.label"
              :value="angle.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="action-buttons">
        <el-button
            type="primary"
            icon="Search"
            @click="applyFilters"
        >
          应用筛选
        </el-button>
        <el-button
            icon="Refresh"
            @click="resetFilters"
        >
          重置
        </el-button>
        <el-button
            type="info"
            icon="Download"
            :disabled="filteredData.length === 0"
            @click="exportFilteredData"
        >
          导出数据
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'

const props = defineProps(['data'])
const emit = defineEmits(['filter-changed'])

// 响应式数据
const filteredData = ref([])
const filterForm = reactive({
  timeRange: [0, 0],
  altitudeRange: [0, 0],
  velocityRange: [0, 0],
  heading: []
})

// 计算属性
const minTime = computed(() => {
  if (!props.data.length) return 0
  return Math.min(...props.data.map(d => d.time))
})

const maxTime = computed(() => {
  if (!props.data.length) return 0
  return Math.max(...props.data.map(d => d.time))
})

const maxAltitude = computed(() => {
  if (!props.data.length) return 10000
  return Math.ceil(Math.max(...props.data.map(d => d.position.hei)) / 1000) * 1000
})

const maxVelocity = computed(() => {
  if (!props.data.length) return 1000
  return Math.ceil(Math.max(...props.data.map(d => d.velocity.vel)) / 100) * 100
})

const headingOptions = computed(() => {
  const headings = [...new Set(props.data.map(d => Math.floor(d.attitude.head)))]
  return headings.map(h => ({
    value: h,
    label: `${h}°`
  }))
})

const totalCount = computed(() => props.data.length)
const filteredCount = computed(() => filteredData.value.length)

// 格式化时间显示
const formatTime = (value) => {
  return `${value.toFixed(3)} s`
}

// 滑块变化处理
const handleSliderChange = () => {
  // 实时应用筛选（或可根据性能需求节流）
  applyFilters()
}

// 应用筛选
const applyFilters = () => {
  if (!props.data.length) {
    filteredData.value = []
    return
  }

  const filtered = props.data.filter(item => {
    // 时间筛选
    if (item.time < filterForm.timeRange[0] || item.time > filterForm.timeRange[1]) {
      return false
    }

    // 高度筛选
    if (item.position.hei < filterForm.altitudeRange[0] ||
        item.position.hei > filterForm.altitudeRange[1]) {
      return false
    }

    // 速度筛选
    if (item.velocity.vel < filterForm.velocityRange[0] ||
        item.velocity.vel > filterForm.velocityRange[1]) {
      return false
    }

    // 航向筛选
    if (filterForm.heading.length &&
        !filterForm.heading.includes(Math.floor(item.attitude.head))) {
      return false
    }

    return true
  })

  filteredData.value = filtered
  emit('filter-changed', filtered)
}

// 重置筛选
const resetFilters = () => {
  filterForm.timeRange = [minTime.value, maxTime.value]
  filterForm.altitudeRange = [0, maxAltitude.value]
  filterForm.velocityRange = [0, maxVelocity.value]
  filterForm.heading = []
  applyFilters()
}

// 导出筛选后的数据
const exportFilteredData = () => {
  // 这里实现导出逻辑
  console.log('导出数据:', filteredData.value)
  ElMessage.success(`已导出 ${filteredData.value.length} 条数据`)
}

// 监听数据变化并初始化
watch(() => props.data, (newData) => {
  if (newData.length) {
    // 初始化范围值
    filterForm.timeRange = [minTime.value, maxTime.value]
    filterForm.altitudeRange = [0, maxAltitude.value]
    filterForm.velocityRange = [0, maxVelocity.value]
    filterForm.heading = []

    // 应用初始筛选
    applyFilters()
  } else {
    filteredData.value = []
    emit('filter-changed', [])
  }
}, {immediate: true})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.slider-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #606266;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
</style>